let ApigwClient = require('./indexPost');

class KingdeeDepartment {

    /**
     * 构造器
     */
    constructor(clientID, clientSecret, appToken) {
        this.clientID = clientID;
        this.clientSecret = clientSecret;
        this.appToken = appToken;
    }

    /**
     * 新增部门
     */
    async department(data = {}, params = {}) {
        let list;
        try {
            let requestSDK = new ApigwClient(this.clientID, this.clientSecret, this.appToken);
            const api = 'https://api.kingdee.com/jdy/v2/bd/department';
            const resp = await requestSDK.request({
                url: api,
                method: 'post',
                params,
                data
            });
            list = resp.data.data;
        } catch (e) {
            console.error('新增部门', e);
            throw e;
        }
        return list;
    }

    /**
     * 部门列表
     */
    async getDepartment(data = {}, params = {}) {
        let list = [];
        try {
            let requestSDK = new ApigwClient(this.clientID, this.clientSecret, this.appToken);
            const api = 'https://api.kingdee.com/jdy/v2/bd/department';
            const resp = await requestSDK.request({
                url: api,
                method: 'get',
                params,
                data: {
                    page_size: 100
                }
            });
            let total = resp.data.data.total_page;
            for (let i = 1; i < total+1; i++) {
                params.page = i;
                const resp = await requestSDK.request({
                    // 调用api获取商品列表
                    url: api,
                    method: 'get',
                    params
                });
                for (let row of resp.data.data.rows) {
                    list.push(row);
                }
            }
        } catch (e) {
            console.error('部门列表', e);
            throw e;
        }
        return list;
    }
}

module.exports = KingdeeDepartment;
